﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Forms.Core;
using Umbraco.Forms.Core.Attributes;
using Umbraco.Forms.Data;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.property;

namespace ContourStrikesAgain.Providers.WorkflowTypes
{
    public class UpdateUmbracoMember : WorkflowType
    {
        [Setting("Member Type", description = "Map member type",
           control = "ContourStrikesAgain.FieldSettingTypes.MemberPropertyMapper",
           assembly = "ContourStrikesAgain")]
        public string Fields { get; set; }


        public UpdateUmbracoMember()
        {
            this.Id = new Guid("15385410-C9B6-42DB-8397-62ACFC6FA758");
            this.Name = "Update umbraco member";
            this.Description = "Updates the logged in member";

        }

        public override Umbraco.Forms.Core.Enums.WorkflowExecutionStatus Execute(Record record, RecordEventArgs e)
        {
            if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && System.Web.Security.Membership.GetUser() != null)
            {
                Dictionary<string, string> mappings = new Dictionary<string, string>();
                int mtId = 0;

                string nameMapping = "NodeName";
                string loginMapping = "Login";
                string emailMapping = "Email";
                string passwordMapping = "Password";

                string[] array = Fields.Trim().Split('|');

                foreach (string s in array)
                {
                    string[] a = s.Trim().Split(',');

                    if (a.Count() == 1 && s.Trim().Length >= 4)
                    {

                        if (mtId == 0)
                            int.TryParse(s.Trim(), out mtId);

                    }
                    else if (a.Count() == 3)
                    {

                        string mapping = "";

                        if (!string.IsNullOrEmpty(a[2]))
                            mapping = record.RecordFields[new Guid(a[2])].ValuesAsString();
                        else if (!string.IsNullOrEmpty(a[1]))
                            mapping = StringHelper.ParsePlaceHolders(e.Context, record, a[1]);
                        //TODO change _parseAttribute into a helper by itself

                        if ((!string.IsNullOrEmpty(mapping)))
                        {
                            if (a[0] == "__defaultname")
                                nameMapping = mapping;
                            else if (a[0] == "__defaultlogin")
                                loginMapping = mapping;
                            else if (a[0] == "__defaultemail")
                                emailMapping = mapping;
                            else if (a[0] == "__defaultpassword")
                                passwordMapping = mapping;
                            else
                            {
                                mappings.Add(a[0], mapping);
                                LogHelper.Debug(a[0] + " " + mapping);
                            }
                        }
                    }
                }


                int mId = 0;


                if (int.TryParse(System.Web.Security.Membership.GetUser().ProviderUserKey.ToString(), out mId))
                {
                    Member m = new Member(mId);

                    if (m != null)
                    {
                        if (passwordMapping != "Password")
                            m.Password = passwordMapping;

                        if (emailMapping != "Email")
                            m.Email = emailMapping;

                        if (loginMapping != "Login")
                            m.LoginName = loginMapping;

                        foreach (Property p in m.getProperties)
                        {

                            try
                            {

                                if (mappings.ContainsKey(p.PropertyType.Alias))
                                {
                                    switch (((BaseDataType)p.PropertyType.DataTypeDefinition.DataType).DBType)
                                    {
                                        case DBTypes.Date:
                                            p.Value = DateTime.Parse(mappings[p.PropertyType.Alias]);
                                            break;
                                        case DBTypes.Integer:
                                            string v = mappings[p.PropertyType.Alias];
                                            if (v.ToLower() == "true" || v.ToLower() == "false")
                                                p.Value = bool.Parse(v);
                                            else
                                                p.Value = int.Parse(mappings[p.PropertyType.Alias]);
                                            break;
                                        default:
                                            p.Value = mappings[p.PropertyType.Alias];
                                            break;
                                    }
                                }

                            }
                            catch (Exception ex)
                            {
                                LogHelper.Debug(ex.ToString());
                            }


                            m.XmlGenerate(new System.Xml.XmlDocument());
                            m.Save();




                        }
                    }
                }
            }
            return Umbraco.Forms.Core.Enums.WorkflowExecutionStatus.Completed;
        }

        public override List<Exception> ValidateSettings()
        {
            return new List<Exception>();
        }
    }
}